var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.route('/login')
.get(function(req, res){
	res.render('login', {title:'用户登录'});
})
.post(function(req, res){
	var user = {
		username: 'admin',
		password: '12345678'
	}
	// console.log(req.body.username === user.username);
	// console.log(req.body.password === user.password);
	if((req.body.username === user.username) && (req.body.password === user.password)){
		// console.log('Success');
		req.session.user = user;
		res.redirect('/home');
	}else{
		// console.log('Failed');
		req.session.error = "用户名或密码错误";
		res.redirect('/login');
	}
});
router.route('/register')
.get(function(req, res){
	res.render('register', {title:'用户注册'});
})
.post(function(req, res){
	/*res.redirect('/register');*/
})
router.get('/logout', function(req, res){
	req.session.user = null;
	res.redirect('/');
});

router.get('/home', function(req, res){
	authentication(req, res);
	/*var user = {
		username:'admin',
		password:'123456'
	}*/
	res.render('home',{title:'Home'});
});
function authentication(req, res){
	if(!req.session.user) {
		req.session.error = '请先登录';
		return res.redirect('/login');
	}
}

module.exports = router;
